
#用于构建消息与alpha通信
#目前仅实现了一部分
#TODO 各种命令代码
BT_HANDSHAKE = 0x01
GET_ACT_LIST = 0x02
EXEC_ACT_LIST = 0x03
PLAY_STOP = 0x05
SOUND_SWITCH = 0x06
PLAY_CONTROL = 0x07

PLAY_COMPLETION = 0x31
SENDING_ACT_LIST = 0x80
COMPLETE_SENDING_ACT_LIST = 0x81

#TODO 各种结果代码
SUCCESS = 0x00
FAILURE_EMPTY_FILE = 0x01
FAILURE_LOW_BATTERY = 0x02

#读取消息，转化为一个字典列表，每个字典包括两项：命令与参数
def readMessage(msgs):
    result = []
    msglist = msgs.split(b'\xfb\xbf')[1:]
    for msg in msglist:
        if(msg[-1]!=0xed or msg[0]-1 != len(msg) or msg[-2]!=(sum(msg[0:-2])%256)):
            continue
        result.append({'command':msg[1],'parameter':msg[2:-2]})
    return result

#构建消息
def makeMessage(command,parameter=b'\x00'):
    header = b'\xfb\xbf'
    length = 5+len(parameter)
    # if(parameter>255):
    #     print("参数太长!")
    #     return None
    check = (length+command+sum(parameter))%256
    result = header + bytes([length,command]) + parameter + bytes([check,0xed])
    return result

def prettyPrint(message):
    #TODO 实现更丰富的消息提示，这个函数目前只能按固定方式打印，没考虑那些参数含义
    msgs = readMessage(message)
    for msg in msgs:
        print("command:{}   data:{}".format(hex(msg['command']),msg['parameter']))

#一些常用消息
def handshake():
    return makeMessage(0x01)

def getActList():
    return makeMessage(0x02)

def pausePlay():
    return makeMessage(0x07,b'\x00')

def continuePLay():
    return makeMessage(0x07,b'\x01')

def execActList(name):
    if(name.__class__.__name__=='str'):
        name=bytes(name,'utf8')
    return makeMessage(0x03,name)

    
